package com.defysoft.waukids.message;


import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;

public class MessageMainWrite extends BaseActivity implements OnClickListener{
	View view;
	Toolbar toolbar;
	Fragment fragment[] = new Fragment[2];
	RadioGroup radioGroup;
	TextView radioButtonOne, radioButtonTwo;
	String choiceRadio;
	TextView title;
	PublicSharedpreferences psf;
	Data_Sharedpreferences.SF_Member member;
	Data_Sharedpreferences.SF_Student student;	
	String  FK_Sch_Mes_Code, FK_Cla_Mes_Code, FK_Stu_Mes_Code, FK_Mem_Mes_Email,
	 Mes_Category, Mes_TypeOne, Mes_TypeTwo, Mes_TypeThree, Mes_TypeFour,
	 Mes_TypeFive, Mes_TypeSix = "";
	
	String PK_Mem_Email, memberPhone;
	
	InputMethodManager ipm;		//키보드 올리고 내리기 설정.
	//양식체크용
	int check = 0;
	public Sqlite_Connect sqlite_Connect;
	private final int WRITE_THREAD = 0;
	private final int SUCCESS_WRITE = 1;
	private final int FAIR_WRITE = 2;
	private final int PHONE_THREAD = 3;
	private final int SUCCESS_PHONE = 4;
	private final int FAIR_PHONE = 5;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.message_main_write);
		PK_Mem_Email = getIntent().getStringExtra("PK_Mem_Email");
		setStartData();
		setToolbar();
		startNetwork(PHONE_THREAD);
		registerReceiver(mToastMessageReceiver, new IntentFilter(
				"com.defysoft.waukids.TOAST_MESSAGE"));
	}

	@Override
	public void setStartData() {
		super.setStartData();
		sqlite_Connect = new Sqlite_Connect(this);
		psf = new PublicSharedpreferences(this);
		psf.setMembersp();
		member = psf.getMembersp();
		if (member.Rank.equals("3")) {
			psf.setStudentsp();
			student = psf.getStudentsp();
		}
		fragment[0] = new MessageMainWriteOneF();
		fragment[1] = new MessageMainWriteTwoF();
		ipm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);		
		title = (TextView)findViewById(R.id.MESSAGE_WRITE_TITLE);
		radioButtonOne = (TextView)findViewById(R.id.MESSAGE_WRITE_CATEGORY_ONE);
		radioButtonTwo = (TextView)findViewById(R.id.MESSAGE_WRITE_CATEGORY_TWO);
		radioButtonOne.setOnClickListener(this);
		radioButtonTwo.setOnClickListener(this);
		//기본 투약의뢰서 보이기
		radioButtonOne.setTextColor(0xff37b34a);
		radioButtonTwo.setTextColor(0xffa6a8ab);
		choiceRadio = "투약의뢰서";
		getSupportFragmentManager().beginTransaction()
		.replace(R.id.MESSAGE_WRITE_FRAGCONTAINER, fragment[0])
		.commitAllowingStateLoss();

	}

	private void setToolbar() {
		toolbar = (Toolbar) findViewById(R.id.MESSAGE_WRITE_TOOLBAR);
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		view = findViewById(R.id.NOTICE_WRITE_TOOLBAR_VIEW_SAVE);
		view.setOnClickListener(this);
	}
	
	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		if(firstThread != null){firstThread.interrupt();}
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case WRITE_THREAD:
					saveThread();
					break;
				case PHONE_THREAD:
					phoneThread();
					break;

				}
			}
		});
		firstThread.start();
	}

	protected void phoneThread() {
		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code=" + CODE_MESSAGE_MAIN_WRITE_PHONE 
					+ "&PK_Mem_Email="+PK_Mem_Email
					));
			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(SUCCESS_PHONE, jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIR_PHONE, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where phoneThread()");
		}
	}

	protected void saveThread() {
		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code=" + CODE_MESSAGE_MAIN_WRITE 
					+ "&FK_Sch_Mes_Code="+ FK_Sch_Mes_Code 
					+ "&FK_Cla_Mes_Code="+ FK_Cla_Mes_Code 
					+ "&FK_Stu_Mes_Code="+ FK_Stu_Mes_Code 
					+ "&FK_Mem_Mes_Email="+ FK_Mem_Mes_Email 
					+ "&Mes_Category="+ Mes_Category 
					+ "&Mes_TypeOne="+ Mes_TypeOne 
					+ "&Mes_TypeTwo="+ Mes_TypeTwo 
					+ "&Mes_TypeThree="+ Mes_TypeThree 
					+ "&Mes_TypeFour="+ Mes_TypeFour 
					+ "&Mes_TypeFive="+ Mes_TypeFive 
					+ "&Mes_TypeSix="+ Mes_TypeSix 
					));
			
			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(SUCCESS_WRITE, jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIR_WRITE, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where saveThread()");
		}
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case SUCCESS_PHONE:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			memberPhone = (String)_message.obj;		
			break;
		case FAIR_PHONE:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
			.show();
			break;
		case SUCCESS_WRITE:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			ipm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);			
			setResult(REFRESH_CODE);
			finish();			
			break;
		case FAIR_WRITE:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;
		case CATCH_EXCEPTION:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"MessageMainWrite", member.Email);
			break;

		}
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.MESSAGE_WRITE_CATEGORY_ONE:
			radioButtonOne.setTextColor(0xff37b34a);
			radioButtonTwo.setTextColor(0xffa6a8ab);
			choiceRadio = "투약의뢰서";
			title.setText(choiceRadio);
			getSupportFragmentManager().beginTransaction()
			.replace(R.id.MESSAGE_WRITE_FRAGCONTAINER, fragment[0])
			.commitAllowingStateLoss();
			break;
		case R.id.MESSAGE_WRITE_CATEGORY_TWO:
			radioButtonOne.setTextColor(0xffa6a8ab);
			radioButtonTwo.setTextColor(0xff37b34a);
			choiceRadio = "귀가동의서";
			title.setText(choiceRadio);
			getSupportFragmentManager().beginTransaction()
			.replace(R.id.MESSAGE_WRITE_FRAGCONTAINER, fragment[1])
			.commitAllowingStateLoss();
			break;
		case R.id.NOTICE_WRITE_TOOLBAR_VIEW_SAVE:
			//통째로 넣자. 투약의뢰서인지 귀가동의서인지에 따라 입력.
			if (choiceRadio.equals("투약의뢰서")) {
				 FK_Sch_Mes_Code = student.School;
				 FK_Cla_Mes_Code =   student.Class;
				 FK_Stu_Mes_Code =  student.Code;
				 FK_Mem_Mes_Email = member.Email;
				 Mes_Category =  "1";
				 Mes_TypeOne =  ((MessageMainWriteOneF)fragment[0]).editText[1].getText().toString();
				 Mes_TypeTwo =  ((MessageMainWriteOneF)fragment[0]).editText[2].getText().toString();
				 Mes_TypeThree =  ((MessageMainWriteOneF)fragment[0]).editText[3].getText().toString();
				 Mes_TypeFour = ((MessageMainWriteOneF)fragment[0]).editText[4].getText().toString();
				 Mes_TypeFive = ((MessageMainWriteOneF)fragment[0]).editText[5].getText().toString();
				 Mes_TypeSix = ((MessageMainWriteOneF)fragment[0]).editText[6].getText().toString();
			}else if (choiceRadio.equals("귀가동의서")) {
				 FK_Sch_Mes_Code =  student.School;
				 FK_Cla_Mes_Code =  student.Class;
				 FK_Stu_Mes_Code =  student.Code;
				 FK_Mem_Mes_Email = member.Email;
				 Mes_Category = "2";
				 Mes_TypeOne =  ((MessageMainWriteTwoF)fragment[1]).editText[1].getText().toString();
				 Mes_TypeTwo =  ((MessageMainWriteTwoF)fragment[1]).editText[2].getText().toString();
				 Mes_TypeThree =  ((MessageMainWriteTwoF)fragment[1]).editText[3].getText().toString();
				 Mes_TypeFour = ((MessageMainWriteTwoF)fragment[1]).editText[4].getText().toString();
				 Mes_TypeFive = ((MessageMainWriteTwoF)fragment[1]).editText[5].getText().toString();
				 Mes_TypeSix = ((MessageMainWriteTwoF)fragment[1]).editText[6].getText().toString();
			}
			
			check_form();

			break;

		default:
			break;
		}
	}
	
	// 네.아니오.선택다이얼로그
	void alertDialog(String string_title, int int_code) {
		final String title = string_title;
		final int code = int_code;
		AlertDialog.Builder builder = new AlertDialog.Builder(
				MessageMainWrite.this);
		AlertDialog alert;
		builder.setMessage(title)
				.setCancelable(false)
				.setPositiveButton("네", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						startNetwork(code);
					}
				})
				.setNegativeButton("아니오",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						});
		alert = builder.create();
		alert.show();
	}
	//모든 양식 체크 
	void check_form(){
		check = 0;
		if (Mes_TypeOne.equals("") ||Mes_TypeTwo.equals("") ||Mes_TypeThree.equals("") ||Mes_TypeFour.equals("") ||Mes_TypeFive.equals("")) {
			Toast.makeText(this, "특이사항을 제외한 모든 내용을 입력해 주세요.", Toast.LENGTH_SHORT).show();
			check = 1;
		} else if (check == 0) {
			alertDialog("제출 하시겠습니까?", WRITE_THREAD);
			
		}

	}
	private final BroadcastReceiver mToastMessageReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			LinearLayout layout = (LinearLayout)getLayoutInflater().inflate(R.layout.toast_layout, null);
			TextView toast_tv = (TextView)layout.findViewById(R.id.TOAST_LAYOUT_TV);
			Toast toast = new Toast(MessageMainWrite.this);
			toast.setView(layout);
			toast_tv.setText(intent.getStringExtra("PUSH_NAME")+" : "+intent.getStringExtra("PUSH_SUB"));
			toast.setDuration(Toast.LENGTH_LONG);
			toast.show();
			
		}
	};
	
}